import { Context, inject, controller, get, provide } from 'midway';
import { Goods } from '../../entity/Goods';
import { Cart } from '../../entity/Cart';
import * as _ from 'lodash';

@provide()
@controller('/')
export class HomeController {

  @inject()
  ctx: Context;

  @get('/')
  async index() {
    const giftArr=await Goods.find({where:{typeCode:'gift',weight:0},skip: 0,take: 2,order:{'id':'DESC'}});
    giftArr.unshift(await Goods.findOne({where:{typeCode:'gift',weight:1},order:{'id':'DESC'}})) 
    const trappingsArr=await Goods.find({where:{typeCode:'trappings',weight:0},skip: 0,take: 2,order:{'id':'DESC'}});
    trappingsArr.unshift(await Goods.findOne({where:{typeCode:'trappings',weight:1},order:{'id':'DESC'}})) 
    const officeArr=await Goods.find({where:{typeCode:'office',weight:0},skip: 0,take: 2,order:{'id':'DESC'}});
    officeArr.unshift(await Goods.findOne({where:{typeCode:'office',weight:1},order:{'id':'DESC'}})) 
    await this.ctx.render('index.html', { giftArr,trappingsArr,officeArr });
  }
  @get('/category')
  async category() {
    await this.ctx.render('category.html', { name: 'midway-nunjucks' });
  }
  @get('/shopcart')
  async shopcart() {
    let {userid}=this.ctx.query
    const cartArr=await Cart.findWithImg({userid})
    let totalPrice:number=_.sumBy(cartArr,x=>parseInt(x['price'])*x['count'])
    await this.ctx.render('shopcart.html', { cartArr,totalPrice });
  }
  @get('/userhome')
  async userhome() {
    await this.ctx.render('userhome.html', { name: 'midway-nunjucks' });
  }
  @get('/category_list')
  async categoryList() {
    await this.ctx.render('category_list.html', { name: 'midway-nunjucks' });
  }
  @get('/views')
  async views() {
    let {gcode}=this.ctx.query
    console.log({gcode});
    const goods=await Goods.findOne({gcode})

    await this.ctx.render('views.html', { goods });
  }
}
